package com.leantech.android.browser.ui.setting

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.cscj.android.repository.db.entity.UserAgentEntity
import com.cscj.android.repository.settings.Settings
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.firstOrNull
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import org.koin.core.component.KoinComponent
import org.koin.core.component.inject

class BrowserSettingViewModel : ViewModel(), KoinComponent {

    private val browserSetting by inject<Settings.BrowserSetting>()

    private val uaSettings: Settings.UserAgentSetting by inject()


    val currentUaFlow = uaSettings.currentUserAgent().stateIn(
        scope = viewModelScope, started = SharingStarted.WhileSubscribed(5000), initialValue = null
    )

    fun userAgentList(): List<UserAgentEntity> {
        return runBlocking {
            uaSettings.userAgentList().first()
        }
    }

    fun switchUserAgent(id: Int) {
        viewModelScope.launch {
            uaSettings.switchUserAgent(id)
        }
    }



    val fontSizeFlow = browserSetting.fontSizeFlow().stateIn(
        scope = viewModelScope, started = SharingStarted.WhileSubscribed(5000), initialValue = 100
    )

    fun getCurrentFontSize(): Int {
        return runBlocking {
            browserSetting.fontSizeFlow().firstOrNull() ?: 100
        }
    }

    fun updateFontSize(fontSize: Int) {
        viewModelScope.launch {
            browserSetting.updateFontSize(fontSize)
        }
    }


    fun getCurrentBlockIntent(): Boolean{
        return runBlocking {
            browserSetting.blockIntentFlow().firstOrNull() ?: false
        }
    }


    fun updateBlockIntent(block: Boolean){
        viewModelScope.launch {
            browserSetting.updateBlockIntent(block)
        }
    }
}